// Package api
// @Author: zhangdi
package sysctrl

import (
	"server/application/db/system/dbdto"
	dbsvc2 "server/application/db/system/dbsvc"
	"server/application/dto"
	"server/pkg/ginp"
	"server/pkg/where"
)

// GetButtonAuthList 获取用户按钮权限列表
func GetButtonAuthList(ctx *ginp.ContextPro) {
	roleIds := dbsvc2.SysUserGetRoleIds(ctx.GetLoginUserId())
	authButtons := dbsvc2.SysRolePermissionGetAuthButton(ctx.GetLoginUserId(), roleIds...)
	ctx.OkJsonData(authButtons)
}

// GetAuthMenuList 获取带有权限控制的菜单列表
func GetAuthMenuList(ctx *ginp.ContextPro) {
	list, err := dbsvc2.SysMenuFindList(where.Format(), nil)
	if err != nil {
		return
	}
	treeList := dbsvc2.BuildMenuTree(list, 0)
	soreTreeList := dbsvc2.SortMenuTree(treeList)
	//权限过滤
	userId := ctx.GetLoginUserId()
	filterTree := dbsvc2.SysMenuAuthFilter(soreTreeList, userId)

	ctx.OkJsonData(filterTree)
}

// SysRolePermissionsSave 保存某个角色的权限
func SysRolePermissionsSave(ctx *ginp.ContextPro) {
	var params *dto.RequestSysRolePermissionsSave
	if err := ctx.ShouldBindJSON(&params); err != nil {
		ctx.ErrJson("请求参数有误" + err.Error())
		return
	}
	params.CreatorId = ctx.GetLoginUserId()
	err := dbsvc2.SysRolePermissionSave(params)
	if err != nil {
		ctx.ErrJson(err.Error())
		return
	}
	ctx.OkJsonData(nil)
}

func SysRolePermissionsCreate(ctx *ginp.ContextPro) {
	var params *dbdto.SysRolePermissionsCreate
	if err := ctx.ShouldBindJSON(&params); err != nil {
		ctx.ErrJson("请求参数有误" + err.Error())
		return
	}
	info, err := dbsvc2.SysRolePermissionsCreate(params)
	if err != nil {
		ctx.ErrJson("创建失败" + err.Error())
		return
	}
	ctx.OkJsonData(info)
}

func SysRolePermissionsUpdate(ctx *ginp.ContextPro) {
	var params *dbdto.SysRolePermissionsUpdate
	if err := ctx.ShouldBindJSON(&params); err != nil {
		ctx.ErrJson("请求参数有误" + err.Error())
		return
	}
	wheres := where.Format(where.OptEqual("id", params.ID))
	err := dbsvc2.SysRolePermissionsUpdate(wheres, params)
	if err != nil {
		ctx.ErrJson("修改失败" + err.Error())
		return
	}
	ctx.OkJson()
}

func SysRolePermissionsDelete(ctx *ginp.ContextPro) {
	var params *dbdto.SysRolePermissionsDelete
	if err := ctx.ShouldBindJSON(&params); err != nil {
		ctx.ErrJson("请求参数有误" + err.Error())
		return
	}

	err := dbsvc2.SysRolePermissionsDelete(where.FormatOne("id", "IN", params.ID))
	if err != nil {
		ctx.ErrJson("删除失败" + err.Error())
		return
	}
	ctx.OkJson()
	return
}

func SysRolePermissionsSearch(ctx *ginp.ContextPro) {
	var params *dto.ReqSearch
	if err := ctx.ShouldBindJSON(&params); err != nil {
		ctx.ErrJson("请求参数有误" + err.Error())
		return
	}
	list, total := dbsvc2.SysRolePermissionsSearch(params.Wheres, params.Extra)

	resp := &dto.RespSearch{
		List:     list,
		Total:    uint(total),
		PageNum:  uint(params.Extra.PageNum),
		PageSize: uint(params.Extra.PageSize),
	}
	ctx.OkJsonData(resp)
}
